#include <buola/buola.h>

#if defined BUOLA_HAVE_OPENNI && !defined BUOLA_HAVE_OPENNI2

#include "ckinectdriver_openni.h"

#include <sys/syscall.h>

namespace buola { namespace cvi {

CKinectDriver::CKinectDriver()
{
    mXNContext.Init();
    
    CreateDeviceList();
}

CKinectDriver::~CKinectDriver()
{

}

CKinectDevice *CKinectDriver::FindDeviceNode(const xn::NodeInfo &pNodeInfo)
{
    for(auto lIt=pNodeInfo.GetNeededNodes().Begin();lIt!=pNodeInfo.GetNeededNodes().End();++lIt)
    {
        std::string lConnectionString=(*lIt).GetCreationInfo();
        
        for(CKinectDevice *lDevice : mDevices)
        {
            if(lDevice->ConnectionString()==lConnectionString)
                return lDevice;
        }
    }
    
    return nullptr;
}

void CKinectDriver::CreateDeviceList()
{
    //enumerate devices
    static xn::NodeInfoList lNodeInfoList;
    XnStatus lStatus=mXNContext.EnumerateProductionTrees(XN_NODE_TYPE_DEVICE,nullptr,lNodeInfoList);
    
    if(lNodeInfoList.Begin()==lNodeInfoList.End()) //no node found
        return;

    if(lStatus!=XN_STATUS_OK)
        throw std::runtime_error("can't enumerate OpenNI devices");

    for(auto lIt=lNodeInfoList.Begin();lIt!=lNodeInfoList.End();++lIt)
    {
        mDevices.emplace_back(new CKinectDevice(mXNContext,*lIt));
    }
}

CKinectDriver &get_kinect_driver()
{
    static CKinectDriver lDriver;
    
    return lDriver;
}

/*namespace cvi*/ } /*namespace buola*/ }

#endif
